package cn.laixueit.service;

import cn.laixueit.client.BrandClient;
import cn.laixueit.client.CategoryClient;
import cn.laixueit.client.GoodsClient;
import cn.laixueit.client.SpecClient;
import cn.laixueit.pojo.item.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class GoodsWebService {

    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private SpecClient specClient;

    public Map<String, Object> loadData(Long spuId) {
        HashMap<String, Object> map = new HashMap<>();

        // spu的封装
        Spu spu = goodsClient.findSpuById(spuId).getBody();
        map.put("spu", spu);
        // spu详情的封装
        SpuDetail spuDetail = goodsClient.detail(spuId).getBody();
        map.put("spuDetail", spuDetail);
        // skus集合的封装
        Collection<Sku> skus = goodsClient.list(spuId).getBody();
        map.put("skus", skus);

        // 查询分类，要同时包含分类id和分类名称
        List<Long> cids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
        // 根据分类id集合查询所有分类名称
        List<String> names = categoryClient.names(cids).getBody();
        ArrayList<Map<String, Object>> categorys = new ArrayList<>();
        for (int i = 0; i < cids.size(); i++) {
            HashMap<String, Object> categoryMap = new HashMap<>();
            categoryMap.put("id", cids.get(i));
            categoryMap.put("name", names.get(i));
            categorys.add(categoryMap);
        }
        map.put("categorys",categorys);


        // 品牌
        Brand brand = brandClient.getBrandById(spu.getBrandId()).getBody();
        map.put("brand",brand);

        // 查询规格参数组
        Collection<SpecGroup> groups = specClient.groups(spu.getCid3()).getBody();
        map.put("groups",groups);

        // 查询特殊规格参数
        Collection<SpecParam> specParams = specClient.params(null, spu.getCid3(), null, false).getBody();
        HashMap<Long, String> paramMap = new HashMap<>();
        specParams.forEach(param->{
            paramMap.put(param.getId(),param.getName());
        });

        map.put("paramMap",paramMap);

        return map;
    }
}
